package com.eostoken.eos_wallet.ui.fragment;

import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ArrayUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.ui.fragmentfactory.FragmentFactory;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.fredy.mvp.BasePresenter;
import com.fredy.mvp.BaseView;
import com.fredy.mvp.Model;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIFloatLayout;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import party.loveit.bip44forandroidlibrary.core.ECKey;
import party.loveit.bip44forandroidlibrary.utils.Bip44Utils;
import party.loveit.eosforandroidlibrary.Ecc;

import static com.eostoken.eos_wallet.utils.Constants.ACTIVE;
import static com.eostoken.eos_wallet.utils.Constants.CONFIRM_MNEMONIC;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_ACCOUNT_NAME;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_HINT;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_WALLET_PASSWORD;

public class ConfirmMnemonicFragment extends BaseFragment {

    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;
    @BindView(R.id.mnemonicTextLayout)
    QMUIFloatLayout mnemonicTextLayout;
    @BindView(R.id.mnemonicTagLayout)
    QMUIFloatLayout mnemonicTagLayout;

    private List<String> shuffleList = new ArrayList<>();
    private List<String> confirmList = new ArrayList<>();
    private List<String> originList;
    private String accountname;
    private String password;
    private String hint;
    private String privatekey;
    private String publicKey;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_confirm_mnemonic;
    }

    @Override
    protected void initData() {
        originList = getArguments().getStringArrayList(Constants.EXTRA_WALLET_MNEMONIC);
        accountname = getArguments().getString(Constants.EXTRA_ACCOUNT_NAME, "");
        password = getArguments().getString(Constants.EXTRA_WALLET_PASSWORD, "");
        hint = getArguments().getString(Constants.EXTRA_HINT, "");
    }

    @Override
    protected void initView(View contentView) {
        shuffleList.clear();
        shuffleList.addAll(originList);
        Collections.shuffle(shuffleList);
        topbar.setTitle(StringUtils.getString(R.string.str_backup_mnemonics_confirm));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });
        for (int i = 0; i < shuffleList.size(); i++) {
            addItemToFloatLayout(mnemonicTagLayout, shuffleList.get(i), true);
        }

        int height = SizeUtils.getMeasuredHeight(mnemonicTagLayout);
        mnemonicTextLayout.setMinimumHeight(height);
        DialogHelper.showLongMessageDialog(getActivity(), getString(R.string.str_backup_mnemonics_dialog_title), getString(R.string.str_backup_mnemonics_dialog_msg), getString(R.string.str_backup_mnemonics_dialog_btn), "", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        }, null).show();
    }

    @OnClick(R.id.completeBtn)
    public void onViewClicked() {
        if (ObjectUtils.equals(originList, confirmList)) {
            BigInteger pri = Bip44Utils.getPathPrivateKey(originList, Constants.EOS_PATH);
            privatekey = Ecc.seedPrivate(pri);
            publicKey = Ecc.privateToPublic(privatekey);
            MgpWallet mgpWallet = WalletUtils.addWallet(getActivity(), accountname, password, privatekey, publicKey, originList, hint);
            Fragment fragment = FragmentFactory.getInstatic().getFragment(ACTIVE);
            Bundle bundle = new Bundle();
            bundle.putParcelable(EXTRA_WALLET, mgpWallet);
            bundle.putBoolean("isCreate", true);
            fragment.setArguments(bundle);
            FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "ActiveFragment", true);
        } else {
            ToastUtils.showShort(R.string.str_backup_mnemonics_error);
        }
    }

    private void addItemToFloatLayout(QMUIFloatLayout floatLayout, String text, boolean isClick) {

        TextView textView = new TextView(getActivity());
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        textView.setText(text);


        if (isClick) {
//            boolean isSelect = false;
            int textViewPadding = QMUIDisplayHelper.dp2px(getActivity(), 4);
            textView.setPadding(textViewPadding, textViewPadding, textViewPadding, textViewPadding);
            textView.setGravity(Gravity.CENTER);
            textView.setTag(R.id.mnemon_select_tag, false);
            textView.setBackgroundColor(ColorUtils.getColor(R.color.qmui_config_color_white));

            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isSelect = (boolean) ((TextView) v).getTag(R.id.mnemon_select_tag);
                    int currentChildCount = 0;
                    String text = ((TextView) v).getText().toString().trim();
                    if (isSelect) {
                        ((TextView) v).setTag(R.id.mnemon_select_tag, false);
                        ((TextView) v).setBackgroundColor(ColorUtils.getColor(R.color.qmui_config_color_white));
                        for (int i = 0; i < confirmList.size(); i++) {
                            String str = confirmList.get(i);
                            if (ObjectUtils.equals(str, text)) {
                                currentChildCount = i;
                                confirmList.remove(currentChildCount);
                                removeItemFromFloatLayout(mnemonicTextLayout, currentChildCount);
                            }
                        }
                    } else {

                        ((TextView) v).setTag(R.id.mnemon_select_tag, true);
                        ((TextView) v).setBackgroundColor(ColorUtils.getColor(R.color.qmui_config_color_gray_9));
                        confirmList.add(text);
                        addItemToFloatLayout(mnemonicTextLayout, text, false);
                    }
                }
            });
        }
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(SizeUtils.dp2px(5),
                SizeUtils.dp2px(5),
                SizeUtils.dp2px(5),
                SizeUtils.dp2px(5));
        floatLayout.addView(textView, lp);
    }

    private void removeItemFromFloatLayout(QMUIFloatLayout floatLayout, int index) {
        if (floatLayout.getChildCount() == 0) {
            return;
        }
        floatLayout.removeView(floatLayout.getChildAt(index));
    }

    @Override
    public Model createModel() {
        return null;
    }

    @Override
    public BaseView createView() {
        return null;
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void finishRefresh() {

    }
}
